package com.moter.demo01.requirements.service;

import com.moter.demo01.requirements.dao.OrderDao;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class OrderService {
    private OrderDao orderDao = null;
    public OrderService(){
        orderDao = new OrderDao();
    }

    public void giveOrder(List<String> ids){
        ThreadPoolExecutor threadPool = getThreadPool();
        for (String id : ids) {
            threadPool.execute(()->{orderDao.giveOrder(id);});
        }
        threadPool.shutdown();
    }
    public List<String> searchOrder(){
        return orderDao.searchOrder();
    }

    public void cancerOrder(List<String> ids){
        ThreadPoolExecutor threadPool = getThreadPool();
        for (String id : ids) {
            threadPool.execute(()->{orderDao.cancerOrder(id);});
        }
        threadPool.shutdown();
    }
    //返回线程池的一个实例
    public ThreadPoolExecutor getThreadPool(){
        return new ThreadPoolExecutor(
                5,
                10,//最多10个线程并发执行
                5,//多余线程存活时间
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(30),//阻塞队列
                Executors.defaultThreadFactory(),//线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy());//拒绝策略
    }
}
